﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.Specialized;
using System.Deployment.Application;
using System.IO;
using System.Reflection;
using Microsoft.Win32;
using System.Web;
using System.Windows.Interop;

namespace jKinect.Browser
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class jKinectBrowserWindow : Window
    {
        jKinectExperienceParameter KXParameters;

        public jKinectBrowserWindow()
        {
            RegisterWebControlFeatures();
            InitializeComponent();
			GenerateSwitchToMonitorMenu();
            txtStatus.Text = "No Kinect";
            jKinectBrowserControl1.jKinectInjector.KinectGestureManager.KinectManager.KinectReady += new EventHandler(KinectManager_KinectReady);
        }

        private static void RegisterWebControlFeatures()
        {
            //string exeName = Application.ResourceAssembly.ManifestModule.Name;
            string exeName = System.AppDomain.CurrentDomain.FriendlyName;
            RegistryKey wbEmulationKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION");
            // IE 9 wbEmulationKey.SetValue(exeName, 9999, RegistryValueKind.DWord);
            // IE 11
            wbEmulationKey.SetValue(exeName, 11000, RegistryValueKind.DWord);
            wbEmulationKey.Close();
            RegistryKey wbActiveXLoadingKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_SAFE_BINDTOOBJECT");
            wbActiveXLoadingKey.SetValue(exeName, 1, RegistryValueKind.DWord);
            wbActiveXLoadingKey.Close();
            RegistryKey wbActiveXOverrideSafetyKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY");
            wbActiveXOverrideSafetyKey.SetValue(exeName, 1, RegistryValueKind.DWord);
            wbActiveXOverrideSafetyKey.Close();
        }

        public ContextMenu SystemMenu
        {
            get
            {
                return Resources["systemMenu"] as ContextMenu;
            }
        }

      
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            KXParameters = jKinectExperienceParameter.GetCurrentParameters();
            if (string.IsNullOrEmpty(KXParameters.WebAppUrl))
                jKinectBrowserControl1.Navigate(new Uri("http://jkinect.com"));
            else
            {
                jKinectBrowserControl1.Navigate(new Uri(KXParameters.WebAppUrl));
            }
        }

        private void GenerateSwitchToMonitorMenu()
        {
            if (System.Windows.Forms.Screen.AllScreens.Length > 1)
            {
                int idx = 0;
                foreach (System.Windows.Forms.Screen screen in System.Windows.Forms.Screen.AllScreens)
                {
                    MenuItem menuItem = new System.Windows.Controls.MenuItem()
                    {
                        Header = "Switch to monitor " + (idx + 1),
                    };
                    menuItem.Tag = idx;
                    menuItem.Click += (s, re) =>
                    {
                        int offset = (int)-BorderThickness.Left;
                        int _idx = (int)menuItem.Tag;
                        for (int i = 0; i < _idx; i++)
                        {
                            offset += System.Windows.Forms.Screen.AllScreens[_idx].WorkingArea.Width;
                        }
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            this.WindowState = System.Windows.WindowState.Normal;
                            this.Left = offset;
                            this.WindowState = System.Windows.WindowState.Maximized;
                        }));
                    };
                    SystemMenu.Items.Add(menuItem);
                    idx++;
                }
            }
        }

        void menuItem_Click(object sender, RoutedEventArgs e)
        {
            throw new NotImplementedException();
        }

        void KinectManager_KinectReady(object sender, EventArgs e)
        {
            txtStatus.Text = "Kinect found";
            txtStatus.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void jKinectBrowserControl1_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            txtStatus.Visibility = System.Windows.Visibility.Visible;
            if (e.Uri.ToString().EndsWith(Constants.WEBKINECT_EXT))
            {
                txtStatus.Text = "Loading " + e.Uri.ToString();
                KXParameters = jKinectExperienceParameter.ExtractWebkinectData(e.Uri.ToString());
                KXParameters = jKinectExperienceParameter.AbsolutiseParametersPath(KXParameters);
                Dispatcher.BeginInvoke((Action)(() =>
                    {
                        jKinectBrowserControl1.Navigate(new Uri(KXParameters.WebAppUrl));
                    }));
                e.Cancel = true;
            }
            else
                txtStatus.Text = "Navigating to " + e.Uri.ToString();
        }

        private void jKinectBrowserControl1_Navigated(object sender, NavigationEventArgs e)
        {
            txtStatus.Text = "Navigated";
        }

        private void jKinectBrowserControl1_LoadCompleted(object sender, NavigationEventArgs e)
        {
            try
            {
                this.Title = (Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), true)[0] as AssemblyProductAttribute).Product
                + " - " + jKinectBrowserControl1.WebBrowser.InvokeScript("eval", "document.title").ToString();
            }
            catch
            { }

            if (!string.IsNullOrEmpty(KXParameters.KXPatch))
            {
                if (KXParameters.KXPatch.StartsWith("http"))
                    jKinectBrowserControl1.jKinectInjector.Inject_JScript("KXPatch", new Uri(KXParameters.KXPatch).ToString());
                else
                    jKinectBrowserControl1.jKinectInjector.Inject_InlineJScript("KXPatch", KXParameters.KXPatch);
            }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Up:
                    jKinectBrowserControl1.jKinectInjector.SetElevationAngleDelta(3);
                    break;
                case Key.Down:
                    jKinectBrowserControl1.jKinectInjector.SetElevationAngleDelta(-3);
                    break;
                case Key.D0:
                    jKinectBrowserControl1.jKinectInjector.SetElevationAngle(0);
                    break;
                case Key.PageUp:
                    jKinectBrowserControl1.jKinectInjector.SetElevationAngleBasedOnFOVRatio(0.5f);
                    break;
                case Key.PageDown:
                    jKinectBrowserControl1.jKinectInjector.SetElevationAngleBasedOnFOVRatio(-0.5f);
                    break;
                case Key.System:
                case Key.LeftAlt:
                    SystemMenu.IsOpen = true;
                    break;
                case Key.Escape:
                    this.Close();
                    break;
            }
        }


    }
}
